package com.example.day8_sdcard;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Entity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/***
 1。写数据到SD卡
 2。读数据从SD卡
 3。下载图片到SD卡
 4。读取图片从SD卡
 */
public class Main2Activity extends AppCompatActivity {

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        try {
            FileOutputStream fileOutputStream = openFileOutput("aa.txt", MODE_PRIVATE);
            fileOutputStream.write("sss".getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(new String[]{
                    "android.permission.READ_EXTERNAL_STORAGE",
                            "android.permission.WRITE_EXTERNAL_STORAGE"},
                    101);
        }
        imageView = findViewById(R.id.iv);
        findViewById(R.id.bt_write).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                write();
            }
        });
        findViewById(R.id.bt_read).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                read();
            }
        });
        findViewById(R.id.bt_read_bitmap).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readBitmap();
            }
        });
        findViewById(R.id.bt_write_bitmap).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                writeBitmap();
            }
        });
    }
    //从SD卡读图片
    private void readBitmap() {
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
           // File file = Environment.getExternalStorageDirectory();//跟路径
            //获得sd卡根路径下的Pictures文件夹
            File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath() + "/进度条通知.png");
            imageView.setImageBitmap(bitmap);
        }
    }
    //下载图片到SD卡
    private void writeBitmap() {
        new MyTask().execute("https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2858426577,4189650377&fm=26&gp=0.jpg");
    }
    class MyTask extends AsyncTask<String,String,String>{
        @Override
        protected String doInBackground(String... strings) {
            String url = strings[0];
            FileOutputStream fileOutputStream = null;
            InputStream inputStream =null;
            try {
                HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
                urlConnection.setConnectTimeout(6000);
                urlConnection.setReadTimeout(6000);
                urlConnection.connect();
                inputStream = urlConnection.getInputStream();
                File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
                 fileOutputStream = new FileOutputStream(file.getAbsolutePath() + "/青花瓷.mp3");
                //边读边写
                byte[] bytes = new byte[1024];
                int len =0;
                while ((len = inputStream.read(bytes))!=-1){
                    fileOutputStream.write(bytes,0,len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(fileOutputStream != null){
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(inputStream != null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
            return null;
        }
    }


    //读数据
    private void read() {
        //TODO 1：判断SD卡是否挂载
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File file = Environment.getExternalStorageDirectory();
            //TODO 2:读数据
            StringBuffer stringBuffer = new StringBuffer();
            FileInputStream fileInputStream = null;
            try {
                 fileInputStream = new FileInputStream(file.getAbsolutePath() + "/yaotianxue.txt");
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = fileInputStream.read(bytes))!=-1){
                    String s = new String(bytes, 0, len);
                    stringBuffer.append(s);
                }
                Log.d("ytx", "read: "+stringBuffer.toString());

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(fileInputStream != null){
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    //写数据
    private void write() {
        //TODO 1：判断SD卡是否挂载
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ){
            //TODO 2:获得SD卡根路径
            File file = Environment.getExternalStorageDirectory();
            //TODO 3：写数据
            FileOutputStream fileOutputStream = null;
            try {
                 fileOutputStream = new FileOutputStream(file.getAbsolutePath()+"/yaotianxue.txt");
                fileOutputStream.write("hshshshs".getBytes());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(fileOutputStream != null){
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 101){
            if(grantResults != null && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                Toast.makeText(this, "收于成功", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(this, "授予失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
